<template>
    <div class="page">
        <div class="player top">

            <div class="set winner" v-if="winnerPlayer !== -1 || isDrawGame">
                <img class="badge draw" v-if="isDrawGame" :src="decorates.draw">
                <img class="badge crown" v-else-if="winnerPlayer === 0" :src="decorates.crown">
                <img class="badge fail" v-else :src="decorates.foul">
            </div>

            <div class="set" v-else
                 :class="{active: callingPlayer === 0}"
                 @click="callSet(0)">{{ callingPlayer === 0 ? callingTimer : 'SET' }}
            </div>

            <div class="controller">
                <div class="cards"><img class="stack" :src="decorates.stack" alt="">{{ cards.length }}
                </div>

                <div v-if="cards.length < 3 || deskCards.length >= 24" class="deal disabled">请求发牌</div>
                <template v-else>
                    <template v-if="askingPlayer !== -1">
                        <div v-if="askingPlayer !== 0">
                            <div class="confirm">
                                <div class="action agree" @click="agree">同意</div>
                                <div class="action disagree" @click="disagree">不同意</div>
                            </div>
                        </div>
                        <div v-else class="deal disabled">请求发牌</div>
                    </template>
                    <div v-else class="deal" @click="askingDeal(0)">请求发牌</div>
                </template>
            </div>
            <div class="info">
                <div class="stat found">
                    <img :src="decorates.set">
                    <span class="num">{{ players[0].found.length }}</span></div>
                <div class="stat foul">
                    <img :src="decorates.foul"><span class="num">{{ players[0].foul.length }}</span></div>
            </div>
        </div>

        <div class="desk-container">
            <div class="desk"
                 :class="{level_1: dealMoreTimes <= 1, level_2: dealMoreTimes >= 2 && dealMoreTimes <= 4, level_3: dealMoreTimes > 4}">
                <img class="card" v-for="(card, index) in deskCards" :key="index"
                     @click="selectCard(card)"
                     :class="{active: selectedCards.indexOf(card) > -1}"
                     :src="cardImages['_' + card]">
            </div>
        </div>

        <div class="player bottom">
            <div class="set winner" v-if="winnerPlayer !== -1 || isDrawGame">
                <img class="badge draw" v-if="isDrawGame" :src="decorates.draw">
                <img class="badge crown" v-else-if="winnerPlayer === 1" :src="decorates.crown">
                <img class="badge fail" v-else :src="decorates.foul">
            </div>

            <div class="set" v-else
                 :class="{active: callingPlayer === 1}"
                 @click="callSet(1)">{{ callingPlayer === 1 ? callingTimer : 'SET' }}
            </div>
            <div class="controller">
                <div class="cards">
                    <img class="stack" :src="decorates.stack" alt="">{{ cards.length }}
                </div>
                <div v-if="cards.length < 3  || deskCards.length >= 24" class="deal disabled">请求发牌</div>
                <template v-else>
                    <template v-if="askingPlayer !== -1">
                        <div v-if="askingPlayer !== 1">
                            <div class="confirm">
                                <div class="action agree" @click="agree">同意</div>
                                <div class="action disagree" @click="disagree">不同意</div>
                            </div>
                        </div>
                        <div v-else class="deal disabled">请求发牌</div>
                    </template>
                    <div v-else class="deal" @click="askingDeal(1)">请求发牌</div>

                </template>
            </div>
            <div class="info">
                <div class="stat found">
                    <img :src="decorates.set">
                    <span class="num">{{ players[1].found.length }}</span></div>
                <div class="stat foul">
                    <img :src="decorates.foul"><span class="num">{{ players[1].foul.length }}</span></div>
            </div>
        </div>
    </div>
</template>

<script>
import {reactive, toRefs, watch, onMounted} from "vue";
import {check, find} from "../libs/set";
import * as cardImages from "../assets/set"
import * as audio from "../assets/audio"
import * as decorates from "../assets/decorating"
import {Howl} from "howler"

export default {
    setup(props, ctx) {
        let audioCardClick = new Howl({src: [audio.cardClick]});
        let audioDealCard = new Howl({src: [audio.dealCard]});
        let audioFoul = new Howl({src: [audio.foul]});
        let audioSet = new Howl({src: [audio.set]});
        let audioSetClick = new Howl({src: [audio.setClick]});
        let audioCheerful = new Howl({src: [audio.cheerful]});
        let audioDrawGame = new Howl({src: [audio.drawGame]});

        let state = reactive({
            players: [
                {
                    found: [],
                    foul: [],
                    asking: false
                },
                {
                    found: [],
                    foul: [],
                    asking: false
                }
            ],
            cardImages,
            decorates,
            cards: [], //剩余牌堆
            deskCards: [], //桌面牌堆
            selectedCards: [], //已选择卡片

            dealMoreTimes: 0, //目前请求发牌次数，主要是为了超过12张不需要继续发牌
            callingPlayer: -1, //叫 SET 玩家序号，0为上方玩家，1为下方玩家
            callingTimer: 8, //叫了 SET 的倒数时间
            callingInterval: null,
            askingPlayer: -1, //请求发牌玩家序号
            winnerPlayer: -1,
            isDrawGame: false
        });

        const prepareCards = () => {
            let cards = [];
            for (let i = 1; i <= 81; i++) {
                cards.push(i < 10 ? '0' + String(i) : String(i));
            }
            state.cards = shuffleCards(cards);
        }

        const shuffleCards = (arr) => {
            return arr.map(a => [Math.random(), a])
                .sort((a, b) => a[0] - b[0])
                .map(a => a[1]);
        }

        const dealCards = positions => {
            if (state.cards.length <= 0 || state.deskCards.length >= 24) {
                return
            }

            let dealInterval = setInterval(() => {
                if (positions && positions.length) {
                    let index = positions.shift()
                    state.deskCards[index] = state.cards.shift()
                    audioDealCard.play()
                    return;
                }

                if (state.deskCards.length >= (12 + 3 * state.dealMoreTimes)) {
                    clearInterval(dealInterval)
                    return;
                }

                state.deskCards.push(state.cards.shift())
                audioDealCard.play()
            }, 400)
        }

        const selectCard = (card) => {

            if (state.callingPlayer < 0) {
                return;
            }
            let index = state.selectedCards.indexOf(card)
            if (index > -1) {
                state.selectedCards.splice(index, 1)
            } else {
                if (state.selectedCards.length < 3) {
                    state.selectedCards.push(card)
                }
            }
            audioCardClick.play()
        }

        const callSet = (player) => {

            if (!state.deskCards.length || state.winnerPlayer !== -1) {
                return;
            }

            if (player === state.callingPlayer) {
                audioSetClick.play()
                cancelCalling(true)
            } else if (state.callingPlayer >= 0) {
                return
            } else {
                audioSetClick.play()
                state.callingPlayer = player
                state.callingInterval = setInterval(() => {
                    if (state.callingTimer > 0) {
                        state.callingTimer--
                        if (state.callingTimer <= 3) {
                            audioSetClick.play()
                        }
                    } else {
                        cancelCalling(true)
                    }
                }, 1000)
            }
        }

        const cancelCalling = (isFoul) => {
            state.selectedCards = [];
            if (isFoul) {
                foul()
            }
            clearInterval(state.callingInterval)
            state.callingPlayer = -1
            state.callingTimer = 8
        }

        const foul = () => {
            audioFoul.play()
            if (state.callingPlayer > -1 && state.players[state.callingPlayer].found.length > 0) {
                state.players[state.callingPlayer].found.splice(0, 1)
                state.players[state.callingPlayer].foul += 1
            }
        }

        const foundSet = () => {
            audioSet.play()
            let positions = []
            for (let i = 0; i < state.selectedCards.length; i++) {
                state.players[state.callingPlayer].found.push(state.selectedCards[i])
                if (state.dealMoreTimes > 0) {
                    let index = state.deskCards.indexOf(state.selectedCards[i])
                    state.deskCards.splice(index, 1)
                } else {
                    let index = state.deskCards.indexOf(state.selectedCards[i])
                    //如果还有牌就保留空位
                    //没牌了就直接删除位置
                    if (state.cards.length) {
                        state.deskCards[index] = ''
                        positions.push(index)
                    } else {
                        state.deskCards.splice(index, 1)
                    }
                }
            }

            if (state.dealMoreTimes > 0) {
                state.dealMoreTimes--
            }

            if (positions.length) {
                dealCards(positions)
            }

            cancelCalling(false)
        }

        const askingDeal = (player) => {
            audioSetClick.play()
            state.askingPlayer = player;
        }

        const agree = () => {
            audioSetClick.play()
            state.askingPlayer = -1
            state.dealMoreTimes++
            dealCards()
        }

        const disagree = () => {
            audioDealCard.play()
            state.askingPlayer = -1
        }

        const findSet = () => {
            if (state.deskCards.length === 0) {
                return []
            }
            return find(state.deskCards)
        }

        const endGame = () => {

            let player0 = state.players[0], player1 = state.players[1]

            if (player0.found.length === player1.found.length) {
                if (player0.foul.length === player1.foul.length) { //平手
                    state.isDrawGame = true;
                    audioDrawGame.play()
                    return;
                } else {
                    state.winnerPlayer = player0.foul.length > player1.foul.length ? 0 : 1
                }
            } else {
                state.winnerPlayer = player0.found.length > player1.found.length ? 0 : 1
            }
            audioCheerful.play()
        }

        watch(() => state.selectedCards, cards => {
            if (cards.length === 3) {
                if (check(cards)) {
                    foundSet()
                } else {
                    cancelCalling(true)
                }
            }
        }, {deep: true})

        watch(() => state.deskCards, cards => {
            if (state.cards.length === 0) {
                let sets = findSet()
                if (sets.length === 0) {
                    endGame()
                }
            }
        }, {deep: true})

        prepareCards();

        onMounted(() => {
            dealCards();
        })


        return {
            ...toRefs(state),
            dealCards,
            callSet,
            selectCard,
            askingDeal,
            agree,
            disagree
        }
    }
}
</script>

<style lang="less">

@green: #02a850;
@red: #ea232c;
@purple: #623394;

body {
    margin: 0;
    padding: 0;
}

.page {
    height: calc(100vh - 50px);
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 25px 0;

    .player {
        display: flex;
        height: 100px;
        flex-shrink: 0;
        box-sizing: border-box;
        padding: 10px;
        justify-content: space-between;
        //background: #FFF;
        background: #FAFAFA;

        .info {
            display: flex;
            flex-direction: column;
            justify-content: space-around;
            margin-right: 20px;


            .stat {
                font-size: 20px;
                display: flex;
                align-items: center;

                &.foul {
                    .num {
                        color: #000;
                    }
                }

                img {
                    width: 40px;
                    border: 1px solid #a0a0a0;
                }


                .num {
                    font-size: 24px;
                    color: #e44e5f;
                    font-weight: bold;
                    margin-left: 10px;
                }
            }
        }

        .controller {
            display: flex;
            flex-direction: column;
            justify-content: space-around;
            align-items: center;

            .cards {
                text-align: center;
                font-size: 20px;
                display: flex;
                align-items: center;
                justify-content: center;
                border: 1px solid #EEE;
                width: 86px;

                .stack {
                    width: 20px;
                    margin-right: 10px;
                }
            }

            .deal {
                font-size: 14px;
                padding: 6px 8px;
                background: @green;
                color: #FFF;
                width: 86px;
                box-sizing: border-box;
                text-align: center;

                &.disabled {
                    background: #DDD;
                    color: #666;
                }
            }

            .confirm {
                display: flex;

                .action {
                    font-size: 14px;
                    padding: 6px 8px;
                    color: #FFF;
                    width: 50px;
                    text-align: center;

                    &.agree {
                        background: @green;
                        margin-right: 10px;
                    }

                    &.disagree {
                        background: @red;
                    }
                }
            }
        }


        .set {
            width: 80px;
            height: 80px;
            box-shadow: 0 0 4px #969696;
            font-weight: bold;
            font-size: 32px;
            background: #FFF;
            display: flex;
            align-items: center;
            justify-content: center;

            &.active {
                box-shadow: 0 0 10px #3a5ca9;
                color: @red;
            }

            .badge {
                width: 80px;
                height: 80px;

                &.fail {
                    height: 55px;
                }

                &.draw {
                    width: 70px;
                    height: 40px;
                }
            }
        }

        &.top {
            transform: rotateX(180deg) rotateY(180deg);
            flex-direction: row-reverse;

        }

        &.bottom {
            flex-direction: row-reverse;
        }
    }

    .desk-container {
        background: url("../assets/decorating/desktop.jpg");
        background-size: contain;
        height: calc(100vh - 250px);
        display: flex;
        align-items: center;

        .desk {
            display: grid;
            padding: 4px;
            max-height: 100%;
            box-sizing: border-box;
            grid-column-gap: 4px;
            grid-row-gap: 4px;
            width: 100%;

            &.level_1 {
                grid-template-columns: repeat(3, 1fr);
            }

            &.level_2 {
                grid-template-columns: repeat(4, 1fr);
            }

            &.level_3 {
                grid-template-columns: repeat(6, 1fr);
            }

            .card {
                border: 1px solid #EEE;
                transition: all ease .3s;
                max-width: 100%;

                &.active {
                    box-shadow: 0 0 10px #3a5ca9;
                    z-index: 2;
                }
            }
        }
    }

}
</style>